import Taro from '@tarojs/taro';
import React, { Component } from 'react';
import { View, Image, Video } from '@tarojs/components';
import config from '@/service/config';
import addImg from '@/assets/image/upload/my_camera.png'
// import { ImageUpload } from "@/services/tyre/tyre"
import * as sdk from 'api/fetch';
import moment from 'dayjs';
import './choose-video-view.scss';
export default class ChooseImageView extends Component<any, any> {
  constructor(props) {
    super(props);
    this.state = {
      ...props,
      backData: JSON.stringify(props.files), ///备份数据
      canvasWidth: 500,
      canvasHeight: 375,
    };
    this.checkVideo();
  }

  componentDidUpdate() {
    const { files } = this.props;
    /// 比较数据是否相同 相同则不刷新数据
    let { backData } = this.state;
    if (JSON.stringify(this.props.files) == backData) {
      return;
    }
    backData = JSON.stringify(this.props.files);
    let that = this;
    this.setState(
      {
        files,
        backData,
      },
      () => {
        that.checkVideo();
      },
    );
  }

  onVideoClick = () => {
    let that = this;
    Taro.chooseVideo({
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有，在H5浏览器端支持使用 `user` 和 `environment`分别指定为前后摄像头
      camera: 'back',// 默认拉起后置摄像头
      maxDuration: 15, // 选择视频最大时长
      compressed: true,// 是否压缩
      success: async function (res) {
        // 将选中的视频存在files中
        var tempFilePath = {//返回的视频
          url: res.tempFilePath,
        };
        var thumbTempFilePath = {//返回的视频封面
          url: res.thumbTempFilePath,
        };
        // 发起网络请求 将tag有值的数据进行上传 如果上传成功则移除tag值
        // 获取上传Token
        let { data } = await sdk.rzget('oss/sign', {});
        const successFiles = await (
          await that.uploadFile([tempFilePath, thumbTempFilePath], data.accessid, data.policy, data.signature)
        )
          .filter((item) => item.status === 'success')
          .map((item) => {
            delete item.status;
            delete item.tag;
            return item;
          });

        // 成功的数量<=0则不在走下面流程
        if (successFiles && successFiles.length <= 0) return;

        //对视频及封面数据进行处理
        let obj = { url: '', img: '' }
        obj.url = successFiles[0].url
        obj.img = successFiles[1].url

        // 保存files的值并通知外部刷新数据源
        await that.checkVideo([obj], true);
      },
    });
  };


  // 发起视频上传 异步上传
  uploadFile = async (uploadFiles = [], accessid, policy, signature) => {
    Taro.showLoading({
      title: '视频上传中',
    });
    // let accessId = "LTAI5tHSDf1rq5xdCjFX1ViK"
    // let policy = "eyJleHBpcmF0aW9uIjoiMjAyMy0wNC0wNlQwNzoyODoxNS4wNTJaIiwiY29uZGl0aW9ucyI6W1siY29udGVudC1sZW5ndGgtcmFuZ2UiLDAsMTA0ODU3NjAwMF0sWyJzdGFydHMtd2l0aCIsIiRrZXkiLCJpdHNvdXJjZSJdXX0="
    // let signature = "diR7fQncqdeWdVDVuEapP+gf5Qs="
    const promises = uploadFiles.map((data) => {
      return new Promise((resolve, reject) => {
        Taro.uploadFile({
          url: config.ossHost,
          filePath: data.url,
          name: 'file', // 必须填file。
          formData: {
            OSSAccessKeyId: accessid,
            policy,
            signature,
            key: `itsource/${data.url.slice(data.url.length / 2)}`,
            // 'x-oss-security-token': securityToken // 使用STS签名时必传。
          },
          success: (res) => {
            if (res.statusCode === 204) {
              data.status = 'success';
              data.url = `${config.ossHost}/itsource/${data.url.slice(data.url.length / 2)}`;
              resolve(data);
            }
          },
          fail: (err) => {
            console.log(err);
            Taro.showToast({
              title: '上传失败',
              icon: 'none',
              mask: true,
            });
            /// 上传失败
            data.status = 'fail';
            resolve(data);
          },
        });
      });
    });
    const list = await Promise.all(promises);
    Taro.hideLoading();
    return list;
  };

  checkVideo = async (tmpFileList = [], noti = false) => {
    return new Promise((resolve) => {
      ///1.拿到已经选中的file列表
      let { files, maxCount, mode } = this.state;
      ///2.移除之前的addFile
      const newFiles = files.filter((item, index) => {
        return item.isAdd !== true;
      });

      ///3.合并列表
      if (tmpFileList && tmpFileList.length > 0) {
        newFiles.push(...tmpFileList);
      }

      ///4.数据返回上级
      if (this.props.onFileChange && noti) {
        this.props.onFileChange(newFiles);
      }

      ///5.判断新的addFile
      // files = JSON.parse(JSON.stringify(newFiles));
      // if (files.length < maxCount && mode === 'add') {
      //   /// 添加add按钮
      //   files.push(this.addFile());
      // }
      /// 更新数据会有延迟 setTimeout来解决页面已经刷新 数据还没有变更过来的问题
      setTimeout(() => {
        this.setState(
          {
            files,
          },
          () => {
            resolve(true);
          },
        );
      }, 0);
    });
  };

  // addFile = () => {
  //   return {
  //     url: addImg,
  //     isAdd: true,
  //   };
  // };

  /// 点击删除
  onDeleteImage = (data) => {
    const { files } = this.state;
    const newFiles = files.filter((item) => {
      return item.url != data.url;
    });
    this.setState(
      {
        files: newFiles,
      },
      () => {
        this.checkVideo([], true);
      },
    );
  };

  render() {
    const { files, mode } = this.state;
    return (
      <View className="chooseImageView">
        <View className="choose-img-wrap">
          {files.length > 0 ? files.map((data) => {
            return (
              <View className="img-container" key={data.url}>
                <Video
                  className="img"
                  onClick={this.onVideoClick.bind(this)}
                  src={data.url}
                  initial-time="0"
                  controls={true}
                  autoplay={false}
                  loop={false}
                  muted={false}
                />
                {!(data.isAdd || data.isDefault) && mode === 'add' && (
                  <View className="img-delete" onClick={this.onDeleteImage.bind(this, data)}>
                    删除
                  </View>
                )}
                {data.isDefault && <Image className="img" mode="widthFix" src={addImg}></Image>}
              </View>
            );
          }) :
            <View className="img-container">
              <Image className="img" mode="widthFix" onClick={this.onVideoClick.bind(this)} src={addImg}></Image>
            </View>
          }
        </View>
      </View>
    );
  }
}

// @ts-ignore
ChooseImageView.defaultProps = {
  mode: 'add', /// 显示模式 新增/详情   add | detail
  files: [], /// 图片列表
  maxCount: 9, ///最多上传张数
};
